//
//  FileManager.m
//  ebook
//
//  Created by 吴超飞 on 16/4/14.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "FileManager.h"
#import "Chapter.h"
#import "FmdbAccess.h"
#import "SSZipArchive.h"
#import "AESenAndDe.h"
#import "EncryptData.h"

@implementation FileManager
    
    //从本地文件中读取章节数据
+ (NSString *)readContentBook:(Book *)book chapterId:(NSString *)chapterid{
    
    if(!book||!book.bookid||!book.siteid)return nil;
    
    NSString *filename = [kBookDirectory(book.bookid,book.siteid) stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",chapterid]];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filename])
    return nil;
    NSError *error = nil;
    NSString *content = [NSString stringWithContentsOfFile:filename encoding:kTxtEncoding error:&error];
    //    if(error)
    //        MTLog(@"readContentBookid:%@ chapterId:%@ error:%@",bookid,chapterid,error);
    
    return content;
}
    
//    //章节接口数据写入文件
//+ (BOOL)writeChapterContent:(ChapterContent *)chapterContet{
//    
//    if (!chapterContet.bookid||!chapterContet.chapterid||!chapterContet.chaptercontent||chapterContet.chaptercontent.length==0 ) {
//        return NO;
//    }
//    
//    NSString *filename = [kBookDirectory(chapterContet.bookid) stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",chapterContet.chapterid]];
//    
//    return [[NSFileManager defaultManager] createFileAtPath:filename contents:[chapterContet.chaptercontent dataUsingEncoding:kTxtEncoding allowLossyConversion: YES] attributes:nil];
//}
    
    //直接将同步获取的数据存到本地（因为上面的writeChapterContent经过转码后有问题）
+(BOOL)writeBook:(Book *)book chapterid:(NSString *)chapterid withData:(NSData *)data{
    if (!book||!book.bookid||!book.siteid||!chapterid||data.length==0||!data) {
        return NO;
    }
    
    NSString *filename = [kBookDirectory(book.bookid,book.siteid) stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",chapterid]];
    
    return [[NSFileManager defaultManager] createFileAtPath:filename contents:data attributes:nil];
}
    
    //单个文件的大小，单位为k
+ (float) fileSizeOfContentBook:(Book *)book chapterId:(NSString *)chapterid{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if(!book||!book.bookid||!book.siteid||!chapterid)return 0;
    
    NSString *filename = [kBookDirectory(book.bookid,book.siteid) stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",chapterid]];
    if ([manager fileExistsAtPath:filename]){
        
        return [[manager attributesOfItemAtPath:filename error:nil] fileSize]/1024.0;
    }
    return 0;
}
    
    /**
     *从本地文件中读取一本书文件夹中的所有章节
     */
+ (NSArray *)readBookChapters:(Book *)book {
    
    if(!book||!book.bookid||!book.siteid)return nil;
    NSString *bookPath = kBookDirectory(book.bookid,book.siteid);
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:bookPath])
    return nil;
    
    NSMutableArray *returnArray = [NSMutableArray array];
    //读取书本文件下的所有章节
    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bookPath error:nil];
    
    for (NSString *path in array) {
        if([path hasSuffix:@".txt"]){
            NSInteger index = [path rangeOfString:@"."].location;
            NSString *chapterId = index<path.length?[path substringToIndex:index]:@"";
            [returnArray addObject:chapterId];
        }
    }
    
    return returnArray;
}
    
    //本地下载章节的个数
+ (NSInteger)fileCountInBookDirectory:(Book *)book {
    
    return [FileManager readBookChapters:book].count;
}
    
    /**
     *  读取Books文件夹下的所有的book
     */
+ (NSArray *)readAllBooks {
    
    NSString *bookPath = [NSString stringWithFormat:@"%@", kSaveDirectory];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:bookPath])
    return nil;
    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bookPath error:nil];
    return array;
}
    
+ (BOOL)isExistBookChapters:(Book *)book chapterid:(NSString *)chapterid {
    
    if(!book||!book.siteid||!book.bookid||!chapterid)return NO;
    NSString *bookPath = [NSString stringWithFormat:@"%@/%@.txt", kBookDirectory(book.bookid,book.siteid),chapterid];
    
    return [[NSFileManager defaultManager] fileExistsAtPath:bookPath];
}
    
    //从本地文件中读取整本书的 目录数据
+ (NSArray *)readChapterlist:(Book *)book {
    
    if(!book||!book.bookid||!book.siteid)return nil;
    
    NSDictionary *dict = [FileManager dictOfBookfile:book];
    if(dict){
        return [dict objectForKey:@"chapterList"];
    }
    
    return nil;
}
    
    //从本地文件中读取书籍信息
+ (Book *) readBookinfo:(Book *)book{
    
    if(!book||!book.siteid||!book.bookid)return nil;
    
    NSDictionary *dict = [FileManager dictOfBookfile:book];
    NSDictionary *bookInfo = [dict objectForKey:@"info"];
    if(!bookInfo)return nil;
    Book *mybook = [[Book alloc] initWithDictionary:bookInfo];
    
    return mybook;
}
    
////解密章节列表文件到本地,每次获取新的章节列表后解密一次，后面就不需要每次都解密了
//+(BOOL)decryChapterlist:(NSString *)bookid{
//    
//    NSString *encryBookpath = [kBookDirectory(bookid) stringByAppendingPathComponent:@"chapterlist.json"];
//    NSString *decryBookpath = [kBookDirectory(bookid) stringByAppendingPathComponent:@"list.txt"];
//    if ([FileManager isExistChapterlistAndUnzip:bookid]) {
//        
//        NSData *data = [[NSFileManager defaultManager] contentsAtPath:encryBookpath];
//        dict = [EncryptData decryptData:data];
////        NSString *content = [NSString stringWithContentsOfFile:encryBookpath encoding:NSUTF8StringEncoding error:nil];
////        NSString  *plainText = [AESenAndDe De_Base64andAESDeToString:content];
////
////        //服务端章节列表加密后的字符串尾部含有特殊字符，先截掉这些字符
////        NSRange range = [plainText rangeOfString:@"}" options:NSBackwardsSearch];
////        if(range.length==1 && range.location>0)
////        plainText = [plainText substringToIndex:range.location+1];
////        MTLog(@"解密：%@，结果:%@",range.length==1?@"已截取特殊字符":@"无特殊字符截取",plainText);
//        
//        if([FileManager createFileAtPath:decryBookpath]){
//            if([FileManager writeFileAtPath:decryBookpath content:plainText]){
//                [FileManager deleteFileAtPath:encryBookpath];
//                return YES;
//            }
//        }
//    }
//    return NO;
//}
    
    //读取加密的章节信息文件
+(NSDictionary *)dictOfBookfile:(Book *)book{
    
    NSDictionary *dict = nil;
    NSString *encryBookpath = [kBookDirectory(book.bookid,book.siteid) stringByAppendingPathComponent:@"chapterlist.json"];
    
    if ([FileManager isExistChapterlistAndUnzip:book]) {
       if([FileManager isExistFileAtPath:encryBookpath]){
           NSData *data = [[NSFileManager defaultManager] contentsAtPath:encryBookpath];
           dict = [EncryptData decryptData:data];
       }else{
           MTLog(@"读取章节列表zip文件成功，但未找到chapterlist.json的加密文件");
       }
    }else{
        
        MTLog(@"本地尚且不存在章节列表的zip包");
    }
    return dict;
}
    
+(BOOL)isExistChapterlistAndUnzip:(Book *)book{
    
    NSString *zipBookpath = [kBookDirectory(book.bookid,book.siteid) stringByAppendingPathComponent:@"chapterlist.zip"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:zipBookpath]) {
        return [SSZipArchive unzipFileAtPath:zipBookpath toDestination:kBookDirectory(book.bookid,book.siteid) overwrite:YES password:nil error:nil];
    }
    return NO;
}
    
+ (NSString *)base64Decode:(NSString *)base64String
    {
        NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
        
        NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        
        return string;
    }
    
#pragma mark -
    
    //根据bookid删除某本书的本地缓存数据
+ (BOOL)removeLocalBook:(NSString *)bookid{
    
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *bookPath = [NSString stringWithFormat:@"%@/%@", kSaveDirectory,bookid];
    
    NSError *error = nil;
    BOOL result = [fm removeItemAtPath:bookPath error:&error];
    
    return result;
}
    
    //清理前一个用户的book数据
+ (void)clearBookData {
    
    //获取书架图书数据
    __block NSMutableArray * booksArray=nil;
    [[FmdbAccess shareModel] getBookcases:^(NSMutableArray *casebooks) {
        booksArray = [NSMutableArray arrayWithArray:casebooks];
    }];
    
    //清空书架对应的本地缓存数据
    for (Book *book in booksArray) {
        [self removeLocalBook:book.bookid];
    }
    
    //清空数据库中的书架信息
    [[FmdbAccess shareModel] clearBookcase];
}
    
    //判断文件是否存在
+(BOOL)isExistFileAtPath:(NSString *)filePath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:filePath];
    return isExist;
}
    
    //创建文件
+(BOOL)createFileAtPath:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isSuccess = [fileManager createFileAtPath:path contents:nil attributes:nil];
    if (isSuccess) {
        MTLog(@"文件创建success");
    } else {
        MTLog(@"文件创建fail");
    }
    return isSuccess;
}
    //写文件
+(BOOL)writeFileAtPath:(NSString *)path content:(NSString *)content{
    BOOL isSuccess = [content writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (isSuccess) {
        MTLog(@"写入文件 success");
    } else {
        MTLog(@"写入文件 fail");
    }
    return isSuccess;
}
    
    //删除文件
+(BOOL)deleteFileAtPath:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isSuccess = [fileManager removeItemAtPath:path error:nil];
    if (isSuccess) {
        NSLog(@"删除文件 success");
    }else{
        NSLog(@"删除文件 fail");
    }
    return isSuccess;
}
    
#pragma mark - 字符加密解密
    //字符串解密
+ (NSString*)decryption:(NSString *)content{
    
    NSData *originalData = DataWithString(content);
    NSString *retstr = StringWithData([self encrypt:originalData]);
    
    return retstr;
}
    
    //字符串加密
+ (NSString*)encryption:(NSString *)content{
    
    NSData *encryData = DataWithString(content);
    NSString *decryptStr = StringWithData([self encrypt:encryData]);
    
    return decryptStr;
}
    
+ (NSData *)encrypt:(NSData *)data {
    char *dataP = (char *)[data bytes];
    for (int i = 0; i < data.length; i++) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunsequenced"
        *dataP = *(++dataP) ^ 1;
#pragma clang diagnostic pop
    }
    return data;
}
    
    
    @end
